<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta name="keywords" content="hexo,个人博客,blog" />
  <meta name="description" content="赚钱，裸辞开店！！" />
  <meta http-equiv="x-dns-prefetch-control" content="on">
  <link rel="dns-prefetch" href="https://busuanzi.ibruce.info">
  <link rel="dns-prefetch" href="https://at.alicdn.com">
  
  <link rel="dns-prefetch" href="https://widget.daovoice.io">
  <link rel="dns-prefetch" href="https://widget-static-cdn.daovoice.io">
  <link rel="dns-prefetch" href="https://im.daovoice.io">
  
  
  <link rel="dns-prefetch" href="https://hm.baidu.com/">
  
  
  <link rel="stylesheet" type="text/css" href="/./style/main.css">
	<link rel="shortcut icon" href="/favicon.ico" title="Favicon">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
	<title>js获取当前页面URL</title>
  
  <script>var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="https://hm.baidu.com/hm.js?awwssw1snsnsnn1ndndnndnd99j";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm,s);})();
  </script>
  
  
    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/123456.js","daovoice");daovoice('init',{app_id: "123456"});daovoice('update');
  </script>
  
<meta name="generator" content="Hexo 6.3.0"></head>
<body>
  <canvas id="pattern-placeholder" height="230"></canvas>
<div class="navbar-header">
  <a class="blog-title" href="/">Kyist</a>
  <a class="face-img" href="/">
    <img src="/img/zz.png">
  </a>
</div>
<main>
  <div class="article-title">
    
  
  <h1 class="title">
    js获取当前页面URL
  </h1>
  


    <ul class="article-info">
      <li>
        发布
        <time datetime="2023-02-12T16:18:25.000Z" itemprop="datePublished">2023-02-13</time>
      </li>
      <li>
        
    更新 <time datetime="2023-02-12T16:20:59.398Z" itemprop="dateUpdated">2023-02-13</time>

      </li>
      <li id="busuanzi_container_page_pv">
        阅读 <span id="busuanzi_value_page_pv"></span>
      </li>
    </ul>
  </div>
  <div class="container">
    <div class="article">
      <div class="content">
        
        <p>在WEB开发中，时常会用到javascript来获取当前页面的url网址信息，在这里是我的一些获取url信息的小总结。</p>
<p>下面我们举例一个URL，然后获得它的各个组成部分：<a target="_blank" rel="noopener" href="http://i.jb51.net/EditPosts.aspx?opt=1">http://i.jb51.net/EditPosts.aspx?opt=1</a></p>
<p><strong>1、window.location.href(设置或获取整个 URL 为字符串)</strong></p>
<p>var test &#x3D; window.location.href;<br>alert(test);<br>返回：<a target="_blank" rel="noopener" href="http://i.jb51.net/EditPosts.aspx?opt=1">http://i.jb51.net/EditPosts.aspx?opt=1</a></p>
<p><strong>2、window.location.protocol(设置或获取 URL 的协议部分)</strong></p>
<p>var test &#x3D; window.location.protocol;<br>alert(test);<br>返回：http:</p>
<p><strong>3、window.location.host(设置或获取 URL 的主机部分)</strong></p>
<p>var test &#x3D; window.location.host;<br>alert(test);<br>返回：i.jb51.net</p>
<p><strong>4、window.location.port(设置或获取与 URL 关联的端口号码)</strong></p>
<p>var test &#x3D; window.location.port;<br>alert(test);<br>返回：空字符(如果采用默认的80端口(update:即使添加了:80)，那么返回值并不是默认的80而是空字符)</p>
<p>**5、window.location.pathname(设置或获取与 URL 的路径部分（就是文件地址）)<br>**var test &#x3D; window.location.pathname;<br>alert(test);<br>返回：&#x2F;EditPosts.aspx</p>
<p><strong>6、window.location.search(设置或获取 href 属性中跟在问号后面的部分)</strong></p>
<p>var test &#x3D; window.location.search;<br>alert(test);<br>返回：?opt&#x3D;1</p>
<p>PS：获得查询（参数）部分，除了给动态语言赋值以外，我们同样可以给静态页面，并使用javascript来获得相信应的参数值。</p>
<p><strong>7、window.location.hash(设置或获取 href 属性中在井号“#”后面的分段)</strong></p>
<p>var test &#x3D; window.location.hash;<br>alert(test);<br>返回：空字符(因为url中没有)</p>
<p><strong>8、js获取url中的参数值</strong></p>
<p><strong>一、正则法</strong></p>
<pre><code class="js">function getQueryString(name) &#123;
 var reg = new RegExp(&#39;(^|&amp;)&#39; + name + &#39;=([^&amp;]*)(&amp;|$)&#39;, &#39;i&#39;);
 var r = window.location.search.substr(1).match(reg);
 if (r != null) &#123;
  return unescape(r[2]);
 &#125;
 return null;
&#125;
// 这样调用：
alert(GetQueryString(&quot;参数名1&quot;));
  
alert(GetQueryString(&quot;参数名2&quot;));
  
alert(GetQueryString(&quot;参数名3&quot;));
</code></pre>
<p><strong>二、split拆分法</strong></p>
<pre><code class="js">function GetRequest() &#123;
 var url = location.search; //获取url中&quot;?&quot;符后的字串
 var theRequest = new Object();
 if (url.indexOf(&quot;?&quot;) != -1) &#123;
  var str = url.substr(1);
  strs = str.split(&quot;&amp;&quot;);
  for(var i = 0; i &lt; strs.length; i ++) &#123;
   theRequest[strs[i].split(&quot;=&quot;)[0]] = unescape(strs[i].split(&quot;=&quot;)[1]);
  &#125;
 &#125;
 return theRequest;
&#125;
var Request = new Object();
Request = GetRequest();&lt;br&gt;// var id=Request[&quot;id&quot;]; 
// var 参数1,参数2,参数3,参数N;
// 参数1 = Request[&#39;参数1&#39;];
// 参数2 = Request[&#39;参数2&#39;];
// 参数3 = Request[&#39;参数3&#39;];
// 参数N = Request[&#39;参数N&#39;];
</code></pre>
<p><strong>三、单个参数的获取方法</strong></p>
<pre><code class="js">function GetQueryString(name) &#123; 
 var reg = new RegExp(&quot;(^|&amp;)&quot; + name + &quot;=([^&amp;]*)(&amp;|$)&quot;, &quot;i&quot;); 
 var r = window.location.search.substr(1).match(reg); //获取url中&quot;?&quot;符后的字符串并正则匹配
 var context = &quot;&quot;; 
 if (r != null) 
   context = r[2]; 
 reg = null; 
 r = null; 
 return context == null || context == &quot;&quot; || context == &quot;undefined&quot; ? &quot;&quot; : context; 
&#125;
alert(GetQueryString(&quot;j&quot;));
</code></pre>
<p><strong>javascript 获取当前 URL 参数的两种方法</strong></p>
<pre><code class="js">//返回的是字符串形式的参数，例如：class_id=3&amp;id=2&amp; 
function getUrlArgStr()&#123; 
  var q=location.search.substr(1); 
  var qs=q.split(&#39;&amp;&#39;); 
  var argStr=&#39;&#39;; 
  if(qs)&#123; 
    for(var i=0;i&lt;qs.length;i++)&#123; 
      argStr+=qs[i].substring(0,qs[i].indexOf(&#39;=&#39;))+&#39;=&#39;+qs[i].substring(qs[i].indexOf(&#39;=&#39;)+1)+&#39;&amp;&#39;; 
    &#125; 
  &#125; 
  return argStr; 
&#125; 
//返回的是对象形式的参数 
function getUrlArgObject()&#123; 
  var args=new Object(); 
  var query=location.search.substring(1);//获取查询串 
  var pairs=query.split(&quot;,&quot;);//在逗号处断开 
  for(var i=0;i&lt;pairs.length;i++)&#123; 
    var pos=pairs[i].indexOf(&#39;=&#39;);//查找name=value 
    if(pos==-1)&#123;//如果没有找到就跳过 
      continue; 
    &#125; 
    var argname=pairs[i].substring(0,pos);//提取name 
    var value=pairs[i].substring(pos+1);//提取value 
    args[argname]=unescape(value);//存为属性 
  &#125; 
  return args;xxxxxxxxxx //返回的是字符串形式的参数，
  例如：//返回的是字符串形式的参数，
  例如：class_id=3&amp;id=2&amp; 
  function getUrlArgStr()&#123;   
      var q=location.search.substr(1);   
      var qs=q.split(&#39;&amp;&#39;);
      var argStr=&#39;&#39;;
      if(qs)&#123;     
          for(var i=0;i&lt;qs.length;i++)&#123;       					argStr+=qs[i].substring(0,qs[i].indexOf(&#39;=&#39;))+&#39;=&#39;+qs[i].substring(qs[i].indexOf(&#39;=&#39;)+1)+&#39;&amp;&#39;;     
          &#125;   
      &#125;   
      return argStr; 
  &#125; 
</code></pre>
<p> javascript 获取url中各个部分的功能方法：</p>
<blockquote>
<p>window.location.host; &#x2F;&#x2F;返回url 的主机部分，例如：<a target="_blank" rel="noopener" href="http://www.xxx.com/">www.xxx.com</a><br>window.location.hostname; &#x2F;&#x2F;返回<a target="_blank" rel="noopener" href="http://www.xxx.com/">www.xxx.com</a><br>window.location.href; &#x2F;&#x2F;返回整个url字符串(在浏览器中就是完整的地址栏)，例如：<a target="_blank" rel="noopener" href="http://www.xxx.com/index.php?class_id=3&id=2">www.xxx.com/index.php?class_id=3&amp;id=2</a><br>window.location.pathname; &#x2F;&#x2F;返回&#x2F;a&#x2F;index.php或者&#x2F;index.php<br>window.location.protocol; &#x2F;&#x2F;返回url 的协议部分，例如： http:，ftp:，maito:等等。<br>window.location.port &#x2F;&#x2F;url 的端口部分，如果采用默认的80端口，那么返回值并不是默认的80而是空字符</p>
</blockquote>

      </div>
        <div class="support-author">
          <p>感谢您的阅读。 🙏
          <a href="" target="_blank">关于转载请看这里</a>
            <!--<a class="btn-pay"  href="#pay-modal">¥ 打赏支持</a>-->
          </p>
        </div>
        <!--
            <div class="like ">
              <div class="like-button">
                <a id="like-note" href="">
                  <i class="icon-heart"></i>喜欢
                </a>
              </div>
              <span id="likes-count">256</span>
            </div>
        -->
        <div class="otherLink">
          <div class="previous">
          </div>
          <div class="next">
          </div>
        </div>
        <div class="comments" id="comments">
          

        </div>
      </div>
    </div>
   </div>
</main>
<div class="footer">
  <div class="info">
    <p>
    <a target="_blank" rel="noopener" href="https://hexo.io"> Hexo </a> 强力驱动 |
      <a target="_blank" rel="noopener" href="https://github.com/Youthink/hexo-themes-yearn"> Yearn </a>
      主题
    </p>
    <p>&copy;2013-2018 某某的博客 京ICP备xxxxxx号</p>
  </div>
</div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<script>//console
  var consoleConfig = ''.split(',');
  var canConsole = ;
  var consoleInfo = (function(consoleConfig) {
  if (!canConsole || !consoleConfig || consoleConfig.length < 1) {
    return;
  }
  var consoleColor = '#6190e8';
  var _console;
  var backgroundTextStyle = 'padding: 1px 5px;color: #fff;background: ' + consoleColor + ';'
  var textStyle = 'color: ' + consoleColor + ';';

  consoleConfig.map(o => {
    var num = (o.match(/%c/g) || []).length;
    if(/^http(s)?:\/\//.test(o)) {
      console.log('%c     ', 'background: url(' + o + ') no-repeat left center;font-size: 180px;');
      return;
    }
    if (num > 0) {
      var logArguments = [];
      for (var i = 0; i < num; i++) {
        if (i % 2 === 0) {
          logArguments.push(backgroundTextStyle);
        } else {
          logArguments.push(textStyle);
        }
      }
      (_console = console).log.apply(_console, ['%c' + o, textStyle].concat(logArguments));
      return;
    }
    console.log('%c' + o, textStyle);
  });
}(consoleConfig));</script><script type="text/javascript" src="/./js/main.js"></script>

  <script src="//at.alicdn.com/t/font_159214_mvtxvg9me9.js"></script>
</body>
</html>
